package cipher

import (
	"crypto/ecdsa"
	"crypto/rand"
	"crypto/sha256"
	"crypto/x509"
	"encoding/pem"
	"errors"
	"github.com/obscuren/ecies"
	"log"
)

/**
私钥封装接口
只用用来解密和签名
 */
type EccPrivateCipher struct {
	eccPrivKey        *ecdsa.PrivateKey
	eciesPrivKey      *ecies.PrivateKey
}
func (e *EccPrivateCipher)SetPrivateKey(privateKey []byte) (err error){

	// 2. 获取pem格式的block
	block, _ := pem.Decode(privateKey)
	if block == nil {
		err=errors.New("ecc set private key error!")
		return
	}
	e.eccPrivKey, err = x509.ParseECPrivateKey(block.Bytes)
	if err != nil {
		log.Println(err)
		return
	}

	// 4. 转化为ecdsa格式的priKey
	//var ok bool
	//e.eccPrivKey, ok = privKey.(*ecdsa.PrivateKey)
	//if !ok {
	//	err = errors.New("获取ecc私钥失败")
	//	return
	//}

	// 5. 转化为ecies格式的私钥
	e.eciesPrivKey = ecies.ImportECDSA(e.eccPrivKey)
	return


}
func (e *EccPrivateCipher)Decrypt(src []byte) (dst []byte, err error){

	if e.eciesPrivKey==nil{
		err=errors.New("ECC 用私钥解密时请先设置私钥！")
		return
	}

	// 6. 使用私钥解密
	dst, err = e.eciesPrivKey.Decrypt(rand.Reader,src, nil, nil)
	return
}
func (e *EccPrivateCipher)Sign(src []byte)(dst []byte, err error){
	if e.eccPrivKey==nil{
		err=errors.New("ECC 用私钥签名时请先设置私钥！")
		return
	}
	h:=sha256.Sum256(src)
	// 5.签名获取r和s
	r, s, err := ecdsa.Sign(rand.Reader, e.eccPrivKey, h[:])
	if err != nil {
		return
	}
	dst = append(r.Bytes(), s.Bytes()...)
	return
}

